﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Data;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Web.Compilation;
using System.Data.OleDb;
using System.Web.Helpers;
using System.Collections;
using System.Web.Script.Serialization;

public static class Helper
{
    /// <summary>
    /// 获取url参数值或Form表单值（类型：字符串）
    /// </summary>
    /// <param name="c">任意对象</param>
    /// <param name="key">参数</param>
    /// <param name="filterSQL">是否过滤SQL语句</param>
    /// <returns>url参数值或Form表单值（类型：字符串）</returns>
    public static string GetRequestStr(this object c, string key, bool filterSQL = true)
    {
        string result = HttpContext.Current.Request.Unvalidated(key).ToStr();
        if (filterSQL && result.Trim() != "") result = result.FilterSQL();
        return result;
    }
    /// <summary>
    /// 获取url参数值或Form表单值（类型：整数）
    /// </summary>
    /// <param name="c">任意对象</param>
    /// <param name="key">参数</param>
    /// <returns>url参数值或Form表单值（类型：整数）</returns>
    public static int GetRequestInt(this object c, string key)
    {
        return HttpContext.Current.Request.Unvalidated(key).ToStr().Split(',')[0].ToInt32();
    }
    /// <summary>
    /// 获取url参数值或Form表单值（类型：数字）
    /// </summary>
    /// <param name="c">任意对象</param>
    /// <param name="key">参数</param>
    /// <returns>url参数值或Form表单值（类型：数字）</returns>
    public static double GetRequestDouble(this object c, string key)
    {
        return HttpContext.Current.Request.Unvalidated(key).ToStr().Split(',')[0].ToDouble();
    }

    /// <summary>
    /// 防sql注入处理
    /// </summary>
    /// <param name="sql">输入字符串</param>
    /// <returns>关键字符转全角处理</returns>
    public static string FilterSQL(this string sql)
    {
        Regex re = new Regex(@"(and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join|cmd|'|""|<|>)", RegexOptions.IgnoreCase);
        sql = re.Replace(sql, delegate(Match m)
                                {
                                    return m.Value.ToSBC();
                                });
        return sql;
    }

    /// <summary>
    /// 半角转全角
    /// </summary>
    /// <param name="input">被转换字符串</param>
    /// <returns>结果</returns>
    public static string ToSBC(this string input)
    {
        char[] c = input.ToCharArray();
        for (int i = 0; i < c.Length; i++)
        {
            if (c[i] == 32)
            {
                c[i] = (char)12288;
                continue;
            }
            if (c[i] < 127)
                c[i] = (char)(c[i] + 65248);
        }
        return new string(c);
    }
    /// <summary>
    /// 全角转半角
    /// </summary>
    /// <param name="input">被转换字符串</param>
    /// <returns>结果</returns>
    public static string ToDBC(this string input)
    {
        char[] c = input.ToCharArray();
        for (int i = 0; i < c.Length; i++)
        {
            if (c[i] == 12288)
            {
                c[i] = (char)32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char)(c[i] - 65248);
        }
        return new string(c);
    }

    /// <summary>
    /// 获取配置文件中的appSettings值
    /// </summary>
    /// <param name="c">任意对象</param>
    /// <param name="name">名称</param>
    /// <returns>返回值</returns>
    public static string GetAppSetting(this object c, string key)
    {
        string connstr = "";
        try
        {
            connstr = System.Configuration.ConfigurationManager.AppSettings[key];
        }
        catch
        {
            throw new Exception("配置文件中 appSettings 没有配置 " + key + " 的值！");
        }
        return connstr;
    }
    
    /// <summary>
    /// 获取配置文件中的ConnectionStrings值
    /// </summary>
    /// <param name="c">任意对象</param>
    /// <param name="name">名称（默认值为数据库连接字符串：DBConnectionString）</param>
    /// <returns>返回值</returns>
    public static string GetConnectionString(this object c, string name = "DBConnectionString")
    {
        string connstr = "";
        try
        {
            connstr = System.Configuration.ConfigurationManager.AppSettings[name];
        }
        catch
        {
            throw new Exception("配置文件中 connectionStrings 没有配置 " + name + " 的值！");
        }
        return connstr;
    }

    /// <summary>
    /// 分隔字符串为字符串数组
    /// </summary>
    /// <param name="s">被分隔对象</param>
    /// <param name="split">分隔符（可以是正则表达式）</param>
    /// <param name="option">正则表达式选项</param>
    /// <returns>分割后的字符串数组</returns>
    public static string[] Split(this object s, string split, RegexOptions option = RegexOptions.IgnoreCase)
    {
        return Regex.Split(s.ToStr(), split, option);
    }

    /// <summary>
    /// 转换类型为double，并格式化
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <param name="x">小数位数（默认值-1表示不格式化）</param>
    /// <param name="defaultValue">转换失败后的默认值</param>
    /// <returns>转换后的double</returns>
    public static double ToDouble(this object s, int x = -1, double defaultValue = default(double))
    {
        double tmp = defaultValue;
        try
        {
            if (x == -1)
                tmp = Convert.ToDouble(s.ToStrTrim());
            else
                tmp = Convert.ToDouble(string.Format("{0:F" + x.ToString() + "}", Convert.ToDouble(s.ToStrTrim())));
        }
        catch { }
        return tmp;
    }

    /// <summary>
    /// 转换类型为decimal，并格式化
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <param name="x">小数位数（默认值-1表示不格式化）</param>
    /// <param name="defaultValue">转换失败后的默认值</param>
    /// <returns>转换后的decimal</returns>
    public static decimal ToDecimal(this object s, int x = -1, decimal defaultValue = default(decimal))
    {
        decimal tmp = defaultValue;
        try
        {
            if (x == -1)
                tmp = Convert.ToDecimal(s.ToStrTrim());
            else
                tmp = Convert.ToDecimal(string.Format("{0:F" + x.ToString() + "}", Convert.ToDecimal(s.ToStrTrim())));
        }
        catch { }
        return tmp;
    }

    /// <summary>
    /// 转换类型为float，并格式化
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <param name="x">小数位数（默认值-1表示不格式化）</param>
    /// <param name="defaultValue">转换失败后的默认值</param>
    /// <returns>转换后的float</returns>
    public static float ToFloat(this object s, int x = -1, float defaultValue = default(float))
    {
        float tmp = defaultValue;
        try
        {
            if (x == -1)
                tmp = float.Parse(s.ToStrTrim());
            else
                tmp = float.Parse(string.Format("{0:F" + x.ToString() + "}", float.Parse(s.ToStrTrim())));
        }
        catch { }
        return tmp;
    }

    /// <summary>
    /// 转换类型为int
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <param name="defaultValue">转换失败后的默认值</param>
    /// <returns>转换后的int</returns>
    public static int ToInt32(this object s, int defaultValue = default(int))
    {
        int tmp = defaultValue;
        try
        {
            tmp = Convert.ToInt32(s.ToStrTrim());
        }
        catch { }
        return tmp;
    }
    /// <summary>
    /// 转换类型为Int64
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <param name="defaultValue">转换失败后的默认值</param>
    /// <returns>转换后的Int64</returns>
    public static Int64 ToInt64(this object s, Int64 defaultValue = default(Int64))
    {
        Int64 tmp = defaultValue;
        try
        {
            tmp = Convert.ToInt64(s.ToStrTrim());
        }
        catch { }
        return tmp;
    }

    /// <summary>
    /// 转换类型为DateTime
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <param name="defaultValue">转换失败后的默认值</param>
    /// <returns>转换后的DateTime（转换失败的结果是：9999/01/01 00:00:00）</returns>
    public static DateTime ToDateTime(this object s, DateTime defaultValue = default(DateTime))
    {
        DateTime tmp = defaultValue;
        try
        {
            tmp = Convert.ToDateTime(s.ToStrTrim());
        }
        catch { }
        return tmp;
    }

    /// <summary>
    /// 转换类型为string，并格式化
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <param name="format">格式表达式</param>
    /// <returns>转换后的string</returns>
    public static string ToStr(this object s, string format = "")
    {
        string tmp = "";
        try
        {
            if (format == "")
                tmp = s.ToString();
            else
                tmp = string.Format("{0:" + format + "}", s);
        }
        catch { }
        return tmp;
    }
    /// <summary>
    /// 转换类型为string，并去除首尾空格
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <returns>转换后的string</returns>
    public static string ToStrTrim(this object s)
    {
        string tmp = "";
        try
        {
            tmp = s.ToString().Trim();
        }
        catch { }
        return tmp;
    }
    /// <summary>
    /// 转换类型为string，并去除首尾指定字符
    /// </summary>
    /// <param name="s">被转换对象</param>
    /// <param name="x">要去除的字符</param>
    /// <returns>转换后的string</returns>
    public static string ToStrTrim(this object s, params char[] x)
    {
        string tmp = "";
        try
        {
            tmp = s.ToString().Trim(x);
        }
        catch { }
        return tmp;
    }

    /// <summary>
    /// 转换DataTable为Json字符串
    /// </summary>
    /// <param name="dt">DataTable</param>
    /// <returns>Json字符串</returns>
    public static string ToJson(this DataTable dt)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        ArrayList dic = new ArrayList();
        foreach (DataRow dr in dt.Rows)
        {
            Dictionary<string, object> drow = new Dictionary<string, object>();
            foreach (DataColumn dc in dt.Columns)
            {
                drow.Add(dc.ColumnName, dr[dc.ColumnName].ToStr());
            }
            dic.Add(drow);
        }

        return jss.Serialize(dic);
    }

    /// <summary>
    /// 转换Json字符串为DataTable
    /// </summary>
    /// <param name="json">Json字符串</param>
    /// <returns>DataTable</returns>
    public static DataTable ToDataTable(this string json)
    {
        DataTable dtb = new DataTable();
        try
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ArrayList dic = jss.Deserialize<ArrayList>(json);
            if (dic.Count > 0)
            {
                foreach (Dictionary<string, object> drow in dic)
                {
                    if (drow.Keys.Count() == 0) return dtb;

                    if (dtb.Columns.Count == 0)
                    {
                        foreach (string key in drow.Keys)
                        {
                            dtb.Columns.Add(key, drow[key].GetType());
                        }
                    }

                    DataRow row = dtb.NewRow();
                    foreach (string key in drow.Keys)
                    {
                        row[key] = drow[key];
                    }
                    dtb.Rows.Add(row);
                }
            }
        }
        catch { }

        return dtb;
    }

    /// <summary>
    /// 转换Json字符串为DataRow
    /// </summary>
    /// <param name="json">Json字符串</param>
    /// <returns>DataRow</returns>
    public static DataRow ToDataRow(this string json)
    {
        try
        {
            return ("[" + json + "]").ToDataTable().Rows[0];
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 转换DataRow为Json字符串
    /// </summary>
    /// <param name="dr">DataRow</param>
    /// <returns>Json字符串</returns>
    public static string ToJson(this DataRow dr)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        Dictionary<string, object> drow = new Dictionary<string, object>();
        foreach (DataColumn dc in dr.Table.Columns)
        {
            drow.Add(dc.ColumnName, dr[dc.ColumnName].ToStr());
        }

        return jss.Serialize(drow);
    }

    /// <summary>
    /// SHA1加密
    /// </summary>
    /// <param name="s">被加密字符串</param>
    /// <returns>加密后的字符串</returns>
    public static string getSHA1(this string s)
    {
        byte[] b = System.Security.Cryptography.SHA1.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(s.ToString()));
        return BitConverter.ToString(b);
    }

    /// <summary>
    /// DES加密字符串
    /// </summary>
    /// <returns>加密后的字符串</returns>
    public static string EncryptDES(this string encryptString)
    {
        if (encryptString == "")
            return "";

        try
        {
            byte[] rgbKey = Encoding.UTF8.GetBytes("knzxclas");
            byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());
        }
        catch
        {
            return encryptString;
        }
    }
    /// <summary>
    /// DES解密字符串
    /// </summary>
    /// <returns>解密后的字符串</returns>
    public static string DecryptDES(this string decryptString)
    {
        if (decryptString == "")
            return "";

        try
        {
            byte[] rgbKey = Encoding.UTF8.GetBytes("knzxclas");
            byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = Convert.FromBase64String(decryptString);
            DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(mStream.ToArray());
        }
        catch
        {
            return decryptString;
        }
    }

    /// <summary>
    /// 查询字符串是否包含数组中的某一元素
    /// </summary>
    /// <param name="s">字符串</param>
    /// <param name="str">数组</param>
    /// <returns>false 不包含   true 包含</returns>
    public static bool Contained(this string s, string[] str)
    {
        if (str == null) return false;

        for (int i = 0; i < str.Length; i++)
        {
            if (str[i].Trim() != "" && s.Trim().ToLower().Contains(str[i].Trim().ToLower()))
                return true;
        }
        return false;
    }

    #region SQL语句自动转换为分页SQL
    /// <summary>
    /// 根据输入的SQL语句智能转换并分页，输出总页数和当前页码的数据表
    /// </summary>
    /// <param name="Sql">SQL语句</param>
    /// <param name="TakeNum">每页显示数据行数</param>
    /// <param name="PageMark">页码参数名称</param>
    /// <param name="s">传入值</param>
    /// <returns>ParseSqlList对象实例</returns>
    public static ParseSqlSource ParseSql(this string Sql, object[] s = null, int TakeNum = 10, string PageMark = "PageIndex")
    {
        return ParseSqlWithOther(Sql, "", s, TakeNum, PageMark);
    }
    /// <summary>
    /// 根据输入的SQL语句智能转换并分页，输出总页数和当前页码的数据表
    /// </summary>
    /// <param name="Sql">SQL语句</param>
    /// <param name="connstr">数据库连接字符串</param>
    /// <param name="TakeNum">每页显示数据行数</param>
    /// <param name="PageMark">页码参数名称</param>
    /// <param name="s">传入值</param>
    /// <returns>ParseSqlList对象实例</returns>
    public static ParseSqlSource ParseSqlWithOther(this string Sql, string connstr, object[] s = null, int TakeNum = 10, string PageMark = "PageIndex")
    {
        if (Sql.ToStr() == "")
            throw new Exception("Sql值不能为空！");

        string sql = Sql;
        Regex re = new Regex(@"\([^\(\)]+?\)", RegexOptions.IgnoreCase);
        Match m = re.Match(sql);
        List<string> list = new List<string>();
        int x = 0;
    SqlSet: while (m.Success)
        {
            sql = sql.Replace(m.Value, ".FlyReplaceSql" + x + ".");
            list.Add(m.Value);
            x++;
            m = m.NextMatch();
        }
        m = re.Match(sql);
        if (m.Success) goto SqlSet;

        Regex re1 = new Regex(@"select([\s\S]+)from(?![\]|""])", RegexOptions.IgnoreCase);
        string selectSql = re1.Replace(sql, "select top (.FlyReplaceSkip.+" + TakeNum + ") tempColumn=0, $1from");
        string newSelectSql = SqlReSet(list, "select * from (select row_number()over(order by tempColumn)tempRowNumber,* from (" + selectSql + ")FlyReplaceTmp)FlyReplaceTemp where tempRowNumber>.FlyReplaceSkip.");
        string newCountSql = Regex.Replace("select count(0) from(" + Sql + ")tmp", @"order by[^\)]+", "", RegexOptions.IgnoreCase);

        int Count = 0, PageCount = 1, PageIndex = GetRequestInt(null, PageMark).ToInt32();
        if (connstr == "")
            Count = TSQL.ExecuteScalar(newCountSql, s).ToInt32();
        else
            Count = TSQL.ExecuteScalarWithOther(newCountSql, connstr, s).ToInt32();

        if (Count % TakeNum == 0)
            PageCount = Count / TakeNum;
        else
            PageCount = Count / TakeNum + 1;
        if (PageCount < 1) PageCount = 1;
        if (PageIndex > PageCount) PageIndex = PageCount;
        if (PageIndex < 1) PageIndex = 1;

        int SkipNum = (PageIndex - 1) * TakeNum;

        ParseSqlSource SqlList = new ParseSqlSource();
        SqlList.TakeNum = TakeNum;
        SqlList.PageMark = PageMark;
        SqlList.PageIndex = PageIndex;
        SqlList.Count = Count;
        SqlList.PageCount = PageCount;
        SqlList.Sql = newSelectSql.Replace(".FlyReplaceSkip.", SkipNum.ToString());
        SqlList.OldSql = Sql;
        SqlList.ConnStr = connstr;
        SqlList.ParamValues = s;
        return SqlList;
    }
    private static string SqlReSet(List<string> obj, string sql)
    {
        Regex re = new Regex(@"\.FlyReplaceSql([0-9]+)\.", RegexOptions.IgnoreCase);
        Match m = re.Match(sql);
    SqlReSet: while (m.Success)
        {
            sql = sql.Replace(".FlyReplaceSql" + m.Groups[1].Value + ".", obj[m.Groups[1].Value.ToInt32()]);
            m = m.NextMatch();
        }
        m = re.Match(sql);
        if (m.Success) goto SqlReSet;
        return sql;
    }
    #endregion

    /// <summary>
    /// 检索DataTable
    /// </summary>
    /// <param name="dt">被检索的DataTable</param>
    /// <param name="filterStr">检索条件</param>
    /// <returns>检索结果</returns>
    public static DataTable Where(this DataTable dt, string filterStr)
    {
        DataView dv = dt.DefaultView;
        dv.RowFilter = filterStr;
        return dv.ToTable();
    }
    /// <summary>
    /// 检索DataSet
    /// </summary>
    /// <param name="ds">被检索的DataSet</param>
    /// <param name="filterStr">检索条件</param>
    /// <returns>检索结果</returns>
    public static DataTable Where(this DataSet ds, string filterStr)
    {
        try
        {
            return Where(ds.Tables[0], filterStr);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 导出下载文件
    /// </summary>
    /// <param name="html">被导出的字符串</param>
    /// <param name="fileName">文件名</param>
    public static void DownLoadToFile(this string html, string fileName)
    {
        DownLoadToFile(html, fileName, System.Text.Encoding.Default);
    }
    /// <summary>
    /// 导出下载文件
    /// </summary>
    /// <param name="html">被导出的字符串</param>
    /// <param name="fileName">文件名</param>
    /// <param name="encoding">编码</param>
    public static void DownLoadToFile(this string html, string fileName, System.Text.Encoding encoding)
    {
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
        if (html != "")
        {
            curContext.Response.ContentType = "application/octet-stream";
            curContext.Response.ContentEncoding = encoding;
            curContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + curContext.Server.UrlPathEncode(fileName + ".txt"));
            curContext.Response.Write(html);
            curContext.Response.End();
        }
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="fileName">文件名</param>
    public static void DownLoadFile(this string path, string fileName = "")
    {
        if (fileName == "")
        {
            string[] _tmp = Regex.Split(path, @"(\|/)");
            string[] _tmp1 = _tmp[_tmp.Length - 1].Split('.');
            fileName = _tmp[_tmp.Length - 1].Replace("." + _tmp1[_tmp1.Length - 1], "");
        }
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
        curContext.Response.ContentType = "application/octet-stream";
        curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + curContext.Server.UrlPathEncode(fileName + "." + path.Split('.')[path.Split('.').Length - 1]));
        curContext.Response.WriteFile(curContext.Server.MapPath(path));
        curContext.Response.End();
    }

    /// <summary>
    /// 去除HTML标签
    /// </summary>
    /// <param name="Htmlstring">HTML字符串</param>
    /// <returns>去除HTML标签后的字符串</returns>
    public static string NoHTML(this string Htmlstring)
    {
        if (Htmlstring == "") return "";
        Htmlstring = Htmlstring.Replace("\r\n", "");
        Htmlstring = Regex.Replace(Htmlstring, @"<script.*?</script>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<style.*?</style>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<.*?>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
        Htmlstring = Htmlstring.Replace("<", "");
        Htmlstring = Htmlstring.Replace(">", "");
        Htmlstring = Htmlstring.Replace("\r\n", "");
        Htmlstring = System.Web.HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
        return Htmlstring;
    }
}